package net.qiqbframework.domains.event.domain.types;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.time.Duration;
import java.time.LocalDateTime;

@Getter
public class Feedback implements Serializable {

    protected final String id;

    /**
     * 处理的服务名称
     */
    @Setter
    protected String applicationName;

    @Setter
    protected String instanceName;

    protected FeedbackStatus status;

    @Setter
    protected String processListenerId;

    @Setter
    protected String processId;

    @Setter
    protected LocalDateTime processBeginTime;
    @Setter
    protected LocalDateTime processEndTime;
    @Setter
    protected LocalDateTime feedbackTime;

    /**
     * 处理结果
     */
    @Setter
    protected String processResultMsg;
    private final LocalDateTime domainEventCreateTime;


    public Feedback(String id, FeedbackStatus status, LocalDateTime domainEventCreateTime) {
        this.id = id;
        this.status = status;

        this.domainEventCreateTime = domainEventCreateTime;
    }

    public void feedback(boolean processSuccess, String processResultMsg, LocalDateTime processBeginTime, LocalDateTime processEndTime) {
        this.status = processSuccess ? FeedbackStatus.success : FeedbackStatus.fail;
        this.processResultMsg = processResultMsg;
        this.processBeginTime = processBeginTime;
        this.processEndTime = processEndTime;
        this.feedbackTime = LocalDateTime.now();
    }

    /**
     * 获取处理时间，单位毫秒
     *
     * @return
     */
    public Long getProcessDuration() {
        if (this.processBeginTime == null || this.processEndTime == null) {
            return null;
        }
        return Duration.between(this.processBeginTime, this.processEndTime).toMillis();
    }

    /**
     * 重置反馈信息
     */
    public void reset() {
        this.status = FeedbackStatus.init;
        this.processResultMsg = null;
        this.processBeginTime = null;
        this.processEndTime = null;
    }

    public boolean isSuccess() {
        return this.status == FeedbackStatus.success || this.status == FeedbackStatus.cancel;
    }

    public Long getSubscriptDuration() {

        if (this.processEndTime == null) {
            return null;
        }
        return Duration.between(this.domainEventCreateTime, this.processEndTime).toMillis();

    }
}
